package com.example.library.player;

import android.media.MediaPlayer;

import java.io.IOException;


/**
 * Created by dadong on 2018/8/22.
 * Describe:
 */
public class MyMediaPlayer {
    private static MyMediaPlayer player;
    private MediaPlayer mediaPlayer;

    private MediaPlayer.OnPreparedListener preparedListener;
    private MediaPlayer.OnCompletionListener completionListener;

    //有些地方需要维护一个单利，有些又不需要，因此把构造函数声明为public;
    public MyMediaPlayer() {
        mediaPlayer = new MediaPlayer();
    }

   /* public static MyMediaPlayer getPlayer() {
        if (player == null) {
            synchronized (MyMediaPlayer.class) {
                if (player == null) {
                    player = new MyMediaPlayer();
                }
            }
        }
        return player;
    }*/

    public MediaPlayer.OnPreparedListener getPreparedListener() {
        return preparedListener;
    }

    public void setPreparedListener(MediaPlayer.OnPreparedListener preparedListener) {
        this.preparedListener = preparedListener;
    }

    public MediaPlayer.OnCompletionListener getCompletionListener() {
        return completionListener;
    }

    public void setCompletionListener(MediaPlayer.OnCompletionListener completionListener) {
        this.completionListener = completionListener;
    }


    public void setDataSource(final String path) {
        try {
            if (completionListener != null) {
                mediaPlayer.setOnCompletionListener(completionListener);
            }
            if (preparedListener != null) {
                mediaPlayer.setOnPreparedListener(preparedListener);
            }
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        mediaPlayer.start();
    }

    public boolean isPlaying() {
        return mediaPlayer.isPlaying();
    }

    public void stop() {
        player.stop();
    }

    public void release() {
        mediaPlayer.release();
    }

}
